<?php

namespace App\Http\Controllers\Product;

use App\Models\Product\ProjectProduct;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Helpers\Code;

class ProjectProductController extends Controller
{
    /**
     * @author lcy
     */
    public function __construct()
    {
        $this->_validators();
        $this->model = new ProjectProduct();
    }

    /**
     * 添加项目包含产品
     * @param Request $request
     * @return array
     */
    public function addProjectProduct(Request $request)
    {
        try {
            $data = $request->only($this->model->getFillable());
            $validator = Validator::make($data, $this->rules, $this->messages);
            if ($validator->fails()) {
                return $this->error($validator, Code::SYSTEM_VALIDATOR_ERROR);
            }

            $model = $this->model->addProjectProduct($data);
            $this->checked($model, [
                'null' => 'product.project.project_or_product_non_exist',
                Code::INSIDE_ERROR => 'product.project.product_exist',
            ]);
            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    /**
     * 删除项目包含产品
     * @param $id
     * @return array
     */
    public function deleteProjectProduct($id)
    {
        try {
            $model = $this->model->deleteProjectProduct($id);
            $this->checked($model, [
                'null' => 'common.delete_failure',
            ]);
            return $this->result;
        } catch (\Exception $e) {
            return $this->throwError($e);
        }
    }

    public function _validators()
    {
        $this->rules = [
            'project_id' => 'bail|required|numeric',
            'product_id' => 'bail|required|numeric',
            'case_total' => 'nullable|max:200',
            'money' => 'nullable|numeric',
        ];

        $this->messages = [
            'project_id.required' => trans('product.project.project_id_required'),
            'project_id.numeric' => trans('product.project.project_id_numeric'),
            'product_id.required' => trans('product.project.product_id_required'),
            'product_id.numeric' => trans('product.project.product_id_numeric'),
            'case_total.max' => trans('product.project.case_total_max'),
            'money.numeric' => trans('product.project.money_numeric'),
        ];
    }
}
